import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.misc.IOUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSA {
    public static final String RSA_ALGORITHM = "RSA";
    public static final BASE64Decoder Base64Decoder;
    public static final BASE64Encoder Base64Encoder;

    static {
        Base64Decoder = new BASE64Decoder();
        Base64Encoder = new BASE64Encoder();
    }

    // 获取RSA公钥和私钥
    public static Map<String, String> createKeys(int KeySize) {
        // 为RSA算法创建一个keyPaiGenerator对象
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }
        // 初始化KeyPairGenerator对象, 密钥长度
        kpg.initialize(KeySize);
        // 生成密钥对
        KeyPair keyPair = kpg.generateKeyPair();
        // 获取公钥
        Key publicKey = keyPair.getPublic();
        // base64加密
        String publicKeyStr = Base64Encoder.encode(publicKey.getEncoded());
        // 获取私钥
        Key privateKey = keyPair.getPrivate();
        // base64加密
        String privateKeyStr = Base64Encoder.encode(privateKey.getEncoded());
        // map装载公钥和私钥
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);
        return keyPairMap;
    }

    // RSA切割解密, ENCRYPT_MODE:加密数据, DECRYPT_MODE:解密数据
    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        // 最大块
        int maxBlock = 0;
        // 解密执行
        if (opmode == cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {    // 加密
            maxBlock = keySize / 8-11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    // 可以调用以下doFinal()方法完成加密或解密数据
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        // IOUtils.closeQuietly(out);
        return resultDatas;
    }

    // 公钥获取
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        // 通过 x509 编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64Decoder.decodeBuffer(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    // 公钥加密
    public static String publicEncrypt(String data, RSAPublicKey publicKey) throws Exception{
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encrypt = rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(StandardCharsets.UTF_8), publicKey.getModulus().bitLength());
            return Base64Encoder.encodeBuffer(encrypt);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    // 公钥解密
    public static String publicDecrypt(String data, RSAPublicKey publicKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] decStr = Base64Decoder.decodeBuffer(data);
            byte[] decrypt = rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, decStr, publicKey.getModulus().bitLength());
            return new String(decrypt);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    // 私钥获取
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        // 通过 PKCS#8 编码的 Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8Key = new PKCS8EncodedKeySpec(Base64Decoder.decodeBuffer(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8Key);
        return key;
    }

    // 私钥加密
    public static String privateEncrypt(String data, RSAPrivateKey privateKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] rspcode = rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(StandardCharsets.UTF_8), privateKey.getModulus().bitLength());
            return Base64Encoder.encode(rspcode);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    // 私钥解密
    public static String privateDecrypt(String data, RSAPrivateKey privateKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] rsacode = rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64Decoder.decodeBuffer(data), privateKey.getModulus().bitLength());
            return new String(rsacode);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥
        Map<String, String> keyMap = RSA.createKeys(1024);
        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");
        System.out.println("公钥:\n\r" + publicKey);
        System.out.println("私钥:\n\r" + privateKey);

        System.out.println("\r\n");
        String str = "李消费";

        System.out.println("\r明文: \r\n" + str);
        System.out.println("\r明文大小: " + str.getBytes().length);

        // 公钥加密: 传入明文和公钥加密 = 密文, str = 明文, RSA.getPublicKey(publicKey):公钥base64解密
        String encodeedData = RSA.publicEncrypt(str, RSA.getPublicKey(publicKey));
        System.out.println("公钥加密后密文: \r\n" + encodeedData);

//        // 公钥解密
//        String publicDecode = RSA.publicDecrypt(encodeedData, RSA.getPublicKey(publicKey));
//        System.out.println("公钥加密后: \r\n" + publicDecode);

        // 私钥解密: encodeedData = 密文, RSA.getPrivateKey(privateKey): 私钥base64解密
        String decodeData = RSA.privateDecrypt(encodeedData, RSA.getPrivateKey(privateKey));
        System.out.println("解密后文字: " + decodeData);

    }
}
